home *** CD-ROM | disk | FTP | other *** search
- Path: druid.borland.com!usenet
- From: pete@borland.com (Pete Becker)
- Newsgroups: comp.lang.c++
- Subject: Re: casting w/ virtual base classes
- Date: 15 Apr 1996 23:34:19 GMT
- Organization: Borland International
- Message-ID: <4kumdr$nki@druid.borland.com>
- References: <31728499.6201DD56@unisql.com>
- NNTP-Posting-Host: pbecker.borland.com
- Mime-Version: 1.0
- Content-Type: Text/Plain; charset=ISO-8859-1
- X-Newsreader: WinVN 0.99.5
-
- In article <31728499.6201DD56@unisql.com>, edhill@unisql.com says...
- >
- >I have the following class hierarchy
- >
- >class Derived : public virtual Base {...};
- >
- >Suppose there is a function foo that returns a pointer to a virtual
- >base class.
- >
- > Base* foo(void) {...}
- >
- >Now, in my program I have a variable declared as a pointer to Derived.
- >
- > int main() {
- > Derived *dp;
- > ...
- > exit 0;
- > }
- >
- >Book Explanation:
- >=================
- >In a virtual derivation, the derived class object contains the derived
- >part and a pointer to the virtual base part. The virtual base class is
- >not contained within the derived class object.
- >==================
- >
- >My compiler does not allow either of the two following statements:
- >
- > Derived *dp1 = foo();
- > Derived *dp2 = (Derived *) foo();
- >
- >error: cast: Base* ->derived dp2*; Base is virtual base
- >
- >Ok, fine...
- >
- >However, the following compiles:
- >
- > Derived *dp = (Derived *) (void *) foo();
- >
- >Then, I'm able to access members of Derived and get correct data,
- >remember foo() returns a pointer to a virtual base.
- >
- > dp->num; // for example
- >
- >===
- >Q1: Is the double cast legal? Why? / Why not?
-
- Yes, it is legal. It is not useful, however.
-
- >Q2: How is it possible when from the book explanation, virtual base
- > is in a different address space and pointed to from the derived
- > class object.
-
- It did not say that the virtual base is in a different address space. I have no
- idea why this code happened to work. It was luck, nothing more. Don't do this.
- The only reliable way to get from a pointer to a virtual base to a pointer to
- derived is with a dynamic_cast.
- -- Pete
-
-